package com.qf.day14;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Demo1 {
    public static <K, V> K getKeyByValue(Map<K, V> map, V value) {
        for (Map.Entry<K, V> entry : map.entrySet()) {
            if (value.equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null; // 如果没有找到匹配的key，返回null
    }

    public static void main(String[] args) throws FileNotFoundException {
        String path =  "D:\\QD-2306\\java\\qfcode\\src\\com\\qf\\day14\\IP.txt";
        File file = new File(path);
        Scanner scanner = new Scanner(file);
        List<String> list = new ArrayList<>();
        String line = "";
        while (scanner.hasNextLine()){
           line = scanner.nextLine();
            list.add(line);
        }
        scanner.close();
        //去重
        HashSet<String> hashSet = new HashSet<>(list);
        hashSet.forEach(e-> System.out.println(e));
        //统计
        HashMap<String, Integer> hashMap = new HashMap<>();
        Scanner scanner1 = new Scanner(file);
        String line1= "";
        while (scanner1.hasNextLine()){
            line1 = scanner1.nextLine();
            hashMap.put(line1, hashMap.get(line1)==null?1:hashMap.get(line1)+1);
        }
        //找value最大的
        Set<Map.Entry<String, Integer>> set = hashMap.entrySet();
        set.forEach(e-> System.out.println(e));
        int max = 0;
        for (Map.Entry<String, Integer> entry : set) {
            if(max < entry.getValue()){
                max = entry.getValue();
            }
        }
        System.out.println(getKeyByValue(hashMap, max));
        //将value排序返回前三  TreeSet() 实现Comparator 接口
        Set<Map.Entry<String, Integer>> set1 = new TreeSet<>(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue()-o1.getValue();
            }
        });
        Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
        System.out.println("======================");
        for (Map.Entry<String, Integer> entry : entries) {
            set1.add(entry);
        }
        int count=0;
        for (Map.Entry<String, Integer> entry : set1) {
            count++;
            if (count<=3){
                System.out.println(entry);
            }
        }
    }
}
